/**
 * Created by zhangqi on 2015/4/16.
 * 调用一个简单的下单菜单的例子
 * 参数：
 * @id 容器的div的id 必传
 * @width 容器的宽度 非必传
 * @maxHeight 容器的最大高度  非必传
 * @placeholder  下拉显示框的默认文字 非必传
 * @data  下拉数据 必传
 * @name  组件的name值 必传
 * @chkboxType 下拉树的父子级选择的联动关系 非必传   默认 { "Y": "ps", "N": "ps" }  p:父关联，s:子关联
 * @onSelected  选择后的回调  非必传
 *
 *  new dayhrDropSelect({
        id: "download_excel_templates",
        width: 180,
        maxHeight: 250,
        data: [{id:"id1", name:"选项一"},{id:"id2", name:"选项二"}],
        name: "modelId",
        onSelected:function(oSelect, type){}  oSelect：选择之后的节点数据，type:是手动还是从代码自动触发的（"click","codeAuto"）
    });
 */
define(function(require, exports, module) {
    require("commonStaticDirectory/plugins/dayhrDropSelect/dayhrDropMultipleSelect.css"); //加载样式

    //tree组件
    require("commonStaticDirectory/plugins/zTree/zTreeStyle/zTreeStyle.css");
    require("commonStaticDirectory/plugins/zTree/jquery.ztree.all.min");

    /**
     * 移除数组某个元素
     */
    Array.prototype.removeElement = function (ele) {
        var arr = this;
        for (var i = 0, len = arr.length; i < len; i++) {
            if (arr[i] == ele) {
                arr.splice(i, 1);
                return;
            }
        }
    }

    var dayhrDropSelect = function(){
        this.init.apply(this,arguments);
    }
    dayhrDropSelect.prototype = {
        selectedIds:[],
        selectedVals:[],
        options:{
            id:"dayhr_drop_MulSelect",  //绑定tree的节点
            width:200, //宽度
            maxHeight:200, //最大下拉高度
            data:[],  //加载的数据
            size:"normal",  // 控件大小  normal,small,big
            name:"dayhr_drop_MulSelect_name",
            onSelected:undefined,  // function类型，下拉树选中之后的回调
            isEdit:true, //是否可以编辑
            isShowSearchbox:false  //是否显示搜索框
        },
        init:function(options){
            var t = this;
            t.options = $.extend({},t.options,options);
            t.element = $("#"+ t.options.id);
            if(!t.element[0]){
                alert("请传正确的id参数");
                return false;
            }
            t.renderDom();
        },
        //初始化dom
        renderDom:function(){
            var t = this;
            var _html = '' +
                '<input type="text" autocomplete="off" class="dayhr_drop_MulSelect_input" style="width:'+ (t.options.width-5-31)+'px;" readonly placeholder="'+(t.options.placeholder?t.options.placeholder:"")+'" />' +
                '<input type="hidden" name="'+ t.options.name+'">'+
                '<div class="dayhr_drop_MulSelect_ico"><span style="display: block">▼</span><span>▲</span></div>' +
                '<div class="dayhr_drop_MulSelect_clearico" title="清空所有" style="display: none;">✕</div>' +
                '<div class="dayhr_drop_MulSelect_disable" style="'+ (t.options.isEdit?'display:none':'display:block')+'"></div>'+
                '<div class="dayhr_drop_MulSelect_tree ztree" id="tree-'+ t.options.id+'" style="width:'+ (t.options.width-10)+'px;max-height:'+ t.options.maxHeight+'px;"></div>'+
                '<div class="dayhr_drop_MulSelect_search_tree ztree" id="tree-search-'+ t.options.id+'" style="width:'+ (t.options.width-10)+'px;max-height:'+ t.options.maxHeight+'px;"></div>'+
                '<div id="input-search-'+ t.options.id+'" style="display: none;width:'+ (t.options.width-16)+'px" class="dayhr_drop_MulSelect_search_input"><input type="text" class=" dayhr_drop_MulSelect_input_search" style="width:'+ (t.options.width-60)+'px"><input type="button" class="iconfont_dayhr_base dayhr_search_form_submit" value="&#xe601;"></div>';
            t.element.html(_html);
            t.element.addClass("dayhr_drop_MulSelect_"+ t.options.size).css({width: t.options.width+"px"});
            t.$showInput = t.element.find(".dayhr_drop_MulSelect_input");
            t.$hiddenInput = t.element.find("input[type='hidden']");
            t.bindEvent();
            if(!t.options.isShowSearchbox){
                t.element.find(".dayhr_drop_MulSelect_search_input").hide();
                t.element.find(".dayhr_drop_MulSelect_tree").css({top:"32px"});
            }
            t.initTree();
        },
        //初始化树
        initTree:function(){
            var t = this;
            t.setting = {
                check: {
                    enable: true,
                    chkStyle: "checkbox",
                    radioType: "all",
                    chkboxType: t.options.chkboxType || { "Y": "ps", "N": "ps" }
                },
                view:{showIcon:false},
                callback:{
                    onCheck:function(event, treeId, treeNode){
                        //多选的情况
                        var tree = $.fn.zTree.getZTreeObj(treeId);
                        var nodes = tree.getCheckedNodes();
                        t.selectedIds = [];t.selectedVals = [];
                        if(nodes.length){
                            for(var i= 0;i<nodes.length;i++){
                                if(!nodes[i].isNotAllowSelected){
                                    t.selectedIds.push(nodes[i].id);
                                    t.selectedVals.push(nodes[i].name);
                                }
                            }
                        }

                        t.$showInput.attr("title",t.selectedVals.join("，")).val(t.selectedVals.join("，"));
                        t.$hiddenInput.val(t.selectedIds.join(","));
                    }
                }
            };
            var zNodes;
            if($.isArray(t.options.data) && t.options.data.length){
                zNodes = t.options.data;
            }else if($.isPlainObject(t.options.data) && !$.isEmptyObject(t.options.data)){
                zNodes = [t.options.data];
            }else{
                zNodes = [];
            }
            //多选控件取消禁用checkbox
            if(zNodes.length){
                function setNochkDisabled(aNodes){
                    for(var i=0;i<aNodes.length;i++){
                        if(aNodes[i].chkDisabled){
                            aNodes[i].chkDisabled = false;
                            aNodes[i].isNotAllowSelected = true; //是否不允许选中
                            //aNodes[i].nocheck = true;
                        }
                        if(aNodes[i].children && aNodes[i].children.length){
                            setNochkDisabled(aNodes[i].children);
                        }
                    }
                }
                setNochkDisabled(zNodes);
            }
            $.fn.zTree.init($("#tree-"+t.options.id), t.setting, zNodes);
            t.$showInput = t.element.find(".dayhr_drop_MulSelect_input");
            t.ztreeResultObj = $.fn.zTree.getZTreeObj("tree-"+t.options.id);//缓存起树
        },
        /**
         * 取消主树节点的选中,刷新树即可
         * */
        unSeletedResultTree:function(){
            var t = this;
            t.ztreeResultObj.refresh();
        },
        /**
         * 绑定焦点事件
         * */
        bindEvent:function(){
            var t = this;
            t.$resultTree = t.element.find(".dayhr_drop_MulSelect_tree");
            t.$searchTree = t.element.find(".dayhr_drop_MulSelect_search_tree");
            t.element.on("click",".dayhr_drop_MulSelect_ico",function(event){
                $(".dayhr_drop_MulSelect").find(".ztree").each(function(){
                    if($(this).parent(".dayhr_drop_MulSelect").attr("id") != t.element.attr("id")){
                        $(this).parent(".dayhr_drop_MulSelect").removeClass("openstatus");
                        $(this).parent(".dayhr_drop_MulSelect").find(".dayhr_drop_MulSelect_search_input").hide();
                        $(this).hide();
                    }
                });
                if(t.element.hasClass("openstatus")){
                    t.element.removeClass("openstatus");
                    t.$resultTree.hide(); //隐藏两棵树
                    t.$searchTree.hide();
                    if(t.options.isShowSearchbox){
                        $("#input-search-"+ t.options.id).hide();
                    }
                }else{
                    t.element.addClass("openstatus");
                    t.$resultTree.show(); //只显示主树
                    if(t.options.isShowSearchbox){
                        $("#input-search-"+ t.options.id).show();
                    }
                }
                event.stopPropagation();
            });
            $(document).click(function(event){
                if(!$(event.target).closest("#tree-"+t.options.id + ",#tree-search-"+t.options.id).length && !$(event.target).closest("#input-search-"+ t.options.id).length){
                    t.element.removeClass("openstatus");
                    t.$resultTree.hide();
                    t.$searchTree.hide();
                    $("#input-search-"+ t.options.id).find(".dayhr_drop_MulSelect_input_search").val("");
                    $("#input-search-"+ t.options.id).hide();
                }
            });

            //清空已选内容
            t.element.hover(function () {
                if($.trim($(this).parent().find("input.dayhr_drop_MulSelect_input").val())){
                    $(this).find(".dayhr_drop_MulSelect_clearico").show();
                }
            },function () {
                $(this).find(".dayhr_drop_MulSelect_clearico").hide();
            });
            t.element.on("click",".dayhr_drop_MulSelect_clearico",function () {
                $(this).parent().find("input.dayhr_drop_MulSelect_input").attr("title","").val(""); //清空显示值
                $(this).parent().find("input[type='hidden']").val(""); //清空隐藏域的值
                t.selectedIds = []; //清空
                t.selectedVals = []; //清空

                $.fn.zTree.getZTreeObj("tree-"+t.options.id) && $.fn.zTree.getZTreeObj("tree-"+t.options.id).checkAllNodes(false); //全部取消选择
                $.fn.zTree.getZTreeObj("tree-search-"+t.options.id) && $.fn.zTree.getZTreeObj("tree-search-"+t.options.id).checkAllNodes(false); //全部取消选择
                $(this).hide();
            });


            //绑定搜索事件
            t.bindSearchEvent();
        },
        /**
         * 绑定鼠标输入搜索事件
         * */
        bindSearchEvent:function(){
            var t = this;
            var timer = null;
            t.element.on("keyup",".dayhr_drop_MulSelect_input_search",function(){
                var that = this;
                clearTimeout(timer);
                timer = setTimeout(function(){
                    t.doSearch();
                },300);
            });
        },
        /**
         * 执行搜索
         * */
        doSearch:function(){
            var t = this;
            var sVal =$("#input-search-"+ t.options.id).find(".dayhr_drop_MulSelect_input_search").val();
            if(!sVal){
                t.$hiddenInput.val("");
                t.$resultTree.show();
                t.$searchTree.hide();
                return;
            }
            var aNodes = t.ztreeResultObj.transformToArray(t.ztreeResultObj.getNodes());
            //如果没有树结果
            if(!aNodes.length){
                $("#input-search-"+ t.options.id).find(".dayhr_drop_MulSelect_input_search").val();
                t.$hiddenInput.val("");
                return;
            }
            var aNewNodes = [];
            if(aNodes.length){
                for(var i=0;i<aNodes.length;i++){
                    if(aNodes[i].name.indexOf(sVal) != -1 && !aNodes[i].chkDisabled && !aNodes[i].isParent){  //搜索的时候过滤掉为禁用状态的节点，如果选择组织员工的时候，只有员工节点才能被搜索出来
                        var oTemp = {
                            id:aNodes[i].id,
                            name:aNodes[i].name,
                            chkDisabled:aNodes[i].chkDisabled,
                            fullName:aNodes[i].tip?(aNodes[i] + "（"+aNodes[i].tip+"）"):aNodes[i].name
                        };
                        aNewNodes.push(oTemp);
                    }
                }
                if(aNewNodes.length){
                    //初始化搜索树
                    var search_setting = {
                        check: {
                            enable: true,
                            chkStyle: "checkbox",
                            radioType: "all"
                        },
                        view:{showIcon:false},
                        callback:{
                            onCheck:function(event, treeId, treeNode){
                                //多选的情况
                                var tree = $.fn.zTree.getZTreeObj(treeId);
                                var resultTree=$.fn.zTree.getZTreeObj("tree-"+ t.options.id);
                                var nodes = tree.getNodes();
                                var resultNodes=resultTree.transformToArray(resultTree.getNodes());
                                if(nodes.length && resultNodes.length){
                                    for(var j=0;j<nodes.length;j++){
                                        for(var i=0;i<resultNodes.length;i++){
                                            if(nodes[j].id==resultNodes[i].id){
                                                if(nodes[j].checked){
                                                    resultTree.checkNode(resultNodes[i], true, true,true);
                                                }else {
                                                    resultTree.checkNode(resultNodes[i], false, true,true);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    };
                    $.fn.zTree.init($("#tree-search-"+t.options.id), search_setting, aNewNodes);
                    t.ztreeSearchObj = $.fn.zTree.getZTreeObj("tree-search-"+t.options.id);//缓存起树

                    //勾选search树中已选择的节点
                    var treeObj_search=t.ztreeSearchObj;
                    var nodeAll_search= t.ztreeResultObj.transformToArray(treeObj_search.getNodes());
                    for (var i=0;i<nodeAll_search.length; i++) {
                        for(var j=0;j<t.selectedIds.length;j++){
                            if(nodeAll_search[i].id==t.selectedIds[j]){
                                treeObj_search.checkNode(nodeAll_search[i], true, true);
                            }
                        }
                    }
                    t.$resultTree.hide();
                    t.$searchTree.show();
                    t.element.addClass("openstatus");
                }else{
                    t.$searchTree.hide();
                }
            }
        },
        //获取值
        getValue:function(){
            return this.selectedIds || [];
        },
        //获取显示值
        getShowValue:function(){
            return this.selectedVals|| [];
        },
        /**
         * 判断一个值是否存在于数组中
         * @param {array} arr
         * @param {string} value
         * @return {boolean} 存在返回true,否则返回false
         */
        isInArr: function (arr,value) {
            var r = false;
            for(var i=0;i<arr.length;i++){
                if(arr[i] == value){
                    r = true;
                    break;
                }
            }
            return r;
        },
        //设置值
        setValue:function(val){
            var t = this;
            var isHasSelected = false; //是否成功匹配选中
            if(!val){
                t.$showInput.val("");
                t.$hiddenInput.val("");
                var aCheckedNodes = t.ztreeResultObj.getCheckedNodes(true);
                for (var i=0, l=aCheckedNodes.length; i < l; i++) {
                    t.ztreeResultObj.checkNode(aCheckedNodes[i], false, false);
                }
                return;
            }
            var nodes = t.ztreeResultObj.getNodes();
            var aVal = val.split(",");
            function setSelectedNode(aNodes){
                if(aNodes.length){
                    for(var i=0;i<aNodes.length;i++){
                        if(t.isInArr(aVal,aNodes[i].id) || t.isInArr(aVal,aNodes[i].name)){ //选中匹配,用或的关系来处理，要保证树的每个name唯一，因为后端有时候不好同时传id和name过来
                            isHasSelected = true;
                            t.ztreeResultObj.checkNode(aNodes[i],true,false,true); //布尔值的含义：选中，不关联树，触发onCheck回调

                            //传送父树的ConditionBean,模拟click选中后的回调
                            var oSelect = {
                                key:t.options.name,  //表单项的name
                                values:t.selectedVals,  //表单项的选值
                                nodes:t.ztreeResultObj.getCheckedNodes(true) //节点对象
                            };
                            typeof t.options.onSelected == "function" && t.options.onSelected(oSelect,"codeAuto");  //下拉树选中之后的回调，代码自动触发的
                        }
                        if(aNodes[i].children && aNodes[i].children.length){
                            setSelectedNode(aNodes[i].children);
                        }
                    }
                }
            }
            setSelectedNode(nodes);
            //如果没成功匹配选中就放开选择框，并且清空值
            if(!isHasSelected){
                t.$showInput.val("");
                t.$hiddenInput.val("");
                t.element.find(".dayhr_drop_MulSelect_disable").hide();
            }
        },
        //更新待选值
        updateTreeJson:function(arr){
            var t = this;
            //多选控件取消禁用checkbox
            if(arr.length){
                function setNochkDisabled(aNodes){
                    for(var i=0;i<aNodes.length;i++){
                        if(aNodes[i].chkDisabled){
                            aNodes[i].chkDisabled = false;
                            aNodes[i].isNotAllowSelected = true; //是否不允许选中
                            //aNodes[i].nocheck = true;
                        }
                        if(aNodes[i].children && aNodes[i].children.length){
                            setNochkDisabled(aNodes[i].children);
                        }
                    }
                }
                setNochkDisabled(arr);
            }
            t.ztreeResultObj.destroy();//销毁树
            t.$showInput.val("");
            t.$hiddenInput.val("");
            $.fn.zTree.init($("#tree-"+t.options.id), t.setting, arr); //重新初始化树
            t.ztreeResultObj = $.fn.zTree.getZTreeObj("tree-"+t.options.id);//重新缓存起树
        },
        /**
         * 去除数组中重复的数据
         * @param arr
         * @returns {Array}
         */
        unique:function(array) {
            var r = [];
            for(var i = 0, l = array.length; i < l; i++) {
                for(var j = i + 1; j < l; j++)
                    if (array[i] == array[j]){
                        j = ++i;
                    }
                r.push(array[i]);
            }
            return r;
        }
    }

    module.exports = dayhrDropSelect;
});
